package cn.shyouchi.wuguanjia.android.ui.casualrecord;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.casual.CasualApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.common.Constant;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class SendCasualRecordActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;


    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.textView3)
    TextView mTextView3;
    @BindView(R.id.edit_content)
    EditText mEditContent;
    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotoSnpl;
    @BindView(R.id.activity_add_handover)
    LinearLayout mActivityAddHandover;

    ArrayList<String> photos = new ArrayList<>();


    MenuItem mMenuItem;


    CasualApi mCasualApi;


    @Override
    public int initContentView() {
        return R.layout.activity_send_casual_record;
    }

    @Override
    public void initInjector() {
        mCasualApi = new CasualApi(mContext);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        mPhotoSnpl.init(this);
        mPhotoSnpl.setDelegate(this);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void choicePhotoWrapper() {

        File takePhotoDir = new File(Environment.getExternalStorageDirectory()+"/folder/Images", "TakePhoto");
        startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 3, null, true), REQUEST_CODE_CHOOSE_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            photos.addAll(BGAPhotoPickerActivity.getSelectedImages(data));
            mPhotoSnpl.setData(photos);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            mPhotoSnpl.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        } else if (resultCode == Constant.ACTIVITY_RESPONSE_SUCCESS && requestCode == Constant.ACTIVITY_REQUEST_CODE) {
           // ArrayList<Integer> ids = data.getIntegerArrayListExtra("ids");
            //sendCasual(mEditName.getText().toString(), mEditContent.getText().toString(), mPhotoSnpl.getData(), ids);
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SendCasualRecordActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForCamera(PermissionRequest request) {
        showRationaleDialog("该操作需要使用摄像头，请允许！", request);
    }


    private void showRationaleDialog(String msg, final PermissionRequest request) {
        new android.support.v7.app.AlertDialog.Builder(mContext)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(msg)
                .show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenuItem = menu.add("确定");
        mMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item == mMenuItem) {

            judge();


        }

        return super.onOptionsItemSelected(item);
    }


    private void judge() {

        if (TextUtils.isEmpty(mEditName.getText())) {
            ToastUtil.showToast("标题不能为空");
            return;
        }

        if (TextUtils.isEmpty(mEditContent.getText())) {
            ToastUtil.showToast("内容不能为空");
            return;
        }
        if (mPhotoSnpl.getData()==null){
            return;
        }
        Intent intent=new Intent(mContext,ChoosePersonActivity.class);
        intent.putExtra("title",mEditName.getText().toString());
        intent.putExtra("content",mEditContent.getText().toString());
        intent.putStringArrayListExtra("photo", mPhotoSnpl.getData());
        startActivity(intent);
        finish();

        //startActivityForResult(new Intent(mContext, ChoosePersonActivity.class), Constant.ACTIVITY_REQUEST_CODE);

    }


//    private void sendCasual(String title, String content, ArrayList<String> imgs, ArrayList<Integer> ids) {
//        mCasualApi.sendCasual(title, content, ids, imgs)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
//                    @Override
//                    public void onNext(BaseRequestResult requestResult) {
//
//                        setResult(Constant.ACTIVITY_RESPONSE_NEED_REFRESH);
//                        finish();
//                    }
//                });
//    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        SendCasualRecordActivityPermissionsDispatcher.choicePhotoWrapperWithCheck(this);

    }


    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotoSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, mPhotoSnpl.getMaxItemCount(), models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);

    }

}
